package com.eliza.demo.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.text.isDigitsOnly
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.eliza.demo.R
import com.eliza.demo.vm.UserVm
import com.eliza.library.model.User
import com.eliza.library.tools.InfoTools

class S1Fragment : Fragment() {
    private lateinit var vm: UserVm
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        var view = inflater.inflate(R.layout.fragment_s1, container, false)
        arguments?.getString("user")
        arguments?.getString("pwd")


        view.findViewById<TextView>(R.id.s1_tv_user)
        view.findViewById<TextView>(R.id.s1_tv_pwd)
        activity?.let {
            vm = ViewModelProvider(
                it,
                ViewModelProvider.AndroidViewModelFactory(it.application)
            ).get(UserVm::class.java)
            InfoTools.LogTools("userData", vm.userData.value?.userName ?: "Null")
            InfoTools.LogTools("userData", vm.userData.value?.userAge ?: "Null")
        }
        SetData(view)

        return view
    }

    private fun SetData(view: View) {
        val user = view.findViewById<EditText>(R.id.s1_tv_user)
        val pwd = view.findViewById<EditText>(R.id.s1_tv_pwd)
        view.findViewById<Button>(R.id.buy_btn_login).setOnClickListener {
            if (pwd.text.isEmpty() || !pwd.text.isDigitsOnly()) {
                showNormalDialog()
            } else {
                vm.userData.value = User(user.text.toString(), pwd.text.toString().toInt())
                Navigation.findNavController(view).navigate(R.id.action_s1Fragment_to_s2Fragment)
            }

        }
    }

    private fun showNormalDialog() {
        activity?.let {
            AlertDialog.Builder(it).apply {
                setIcon(R.drawable.img03)
                setTitle("密码错误")
                setMessage("必须是全数字 （狗头护体）");
            }.show()
        }
    }


}